/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jpxx.workflow.engine;

import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.jpxx.workflow.Destination;
import org.jpxx.workflow.Node;
import org.jpxx.workflow.Workflow;
import org.jpxx.workflow.rule.Rule;
import org.jpxx.workflow.rule.RuleExecutor;

/**
 * @author John Lee
 * 
 */
public class WorkFlowEngine implements Engine {

	private static final Logger logger = Logger.getLogger(WorkFlowEngine.class);

	private Map<String, Workflow> map;

	/**
	 * @return the map
	 */
	public final Map<String, Workflow> getMap() {
		return map;
	}

	/**
	 * @param map
	 *            the map to set
	 */
	public final void setMap(Map<String, Workflow> map) {
		this.map = map;
	}

	public void execute(String workflowName, EngineExecutor engineExecutor,
			RuleExecutor ruleExecutor) {
		Workflow workflow = map.get(workflowName);
		if (null == workflow) {
			if (logger.isInfoEnabled()) {
				logger.info(workflowName + " not exist.");
			}
			return;
		}

		Node startNode = workflow.getStart();
		execute(startNode, engineExecutor, ruleExecutor);
	}

	private void execute(Node node, EngineExecutor engineExecutor,
			RuleExecutor ruleExecutor) {
		if (null == node) {
			return;
		}
		Vector<Destination> vector = node.getDestinations();
		if (null == vector) {
			return;
		}

		/**
		 * Execute current node
		 */
		engineExecutor.execute(node.getNodeName());

		for (Destination des : vector) {
			@SuppressWarnings("rawtypes")
			Rule rule = des.getRule();
			if (null != rule && !rule.result(ruleExecutor)) {
				continue;
			}
			execute(des.getNode(), engineExecutor, ruleExecutor);
		}
	}
}
